package cn.stylefeng.guns.core.common.controller;

import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.core.common.constant.Constants;
import cn.stylefeng.guns.core.util.FileUtil;
import cn.stylefeng.guns.core.util.ImgCut;
import cn.stylefeng.guns.core.util.UUIDUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("upload")
public class UploadController extends BaseController {

    @Autowired
    private GunsProperties gunsProperties;

    private String PREFIX = "/common/";

    /**
     * 上传图片
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadImg")
    @ResponseBody
    public Map uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map data = new HashMap() ;
        data.put("code",0);
        data.put("msg","上传成功");
        // 图片路径
        String imgPath = "";
        // 图片名称
        String orgFileName = null;
        // 图片后缀
        String fileExt = null;
        // 文件格式错误信息
        String fileExtError = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            // 获取图片大小
            int picSize = Integer.parseInt(String.valueOf(mf.getSize()));
            // 获取原文件名
            orgFileName = mf.getOriginalFilename();
            String fileName =  mf.getOriginalFilename();
            // 获取图片后缀
            fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Constants.JPG.equals(fileExt) && !Constants.JPEG.equals(fileExt) && !Constants.PNG.equals(fileExt) && !Constants.GIF.equals(fileExt)
                    && !Constants.BMP.equals(fileExt)) {
                fileExtError = "不支持的文件格式";
                data.put("code","1");
                data.put("msg",fileExtError);
                return data;
            } else if (picSize > Constants.ONE_HUNDRED_MB) {
                fileExtError = "图片最大100M";
                data.put("code","2");
                data.put("msg",fileExtError);
                return data;
            } else {
                // 对原文件名进行重命名
                fileName = UUIDUtil.uuid() + "." + fileExt;
                // 返回图片路径
                String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
                imgPath = Constants.NEWS_PATH + fileName;
                File dic = new File(rootPath + Constants.NEWS_PATH);
                if(!dic.exists()){
                    dic.mkdirs();
                }
                //上传至服务器
                String realPath = rootPath + imgPath;
                mf.transferTo(new File(realPath));
                data.put("img_name",orgFileName);
                data.put("img_path",imgPath.replace("\\","/"));
                return data;
            }
        }
        return data;
    }

    /**
     * 上传视频
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadVideo")
    @ResponseBody
    public Map uploadVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map data = new HashMap() ;
        data.put("code",0);
        data.put("msg","上传成功");
        // 视频路径
        String videoPath = "";
        // 视频名称
        String orgFileName = null;
        // 视频后缀
        String fileExt = null;
        // 文件格式错误信息
        String fileExtError = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            // 获取图片大小
            long picSize = mf.getSize();
            // 获取原文件名
            orgFileName = mf.getOriginalFilename();
            String fileName =  mf.getOriginalFilename();
            // 获取图片后缀
            fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Constants.MP4.equals(fileExt) ) {
                fileExtError = "只允许mp4格式";
                data.put("code","1");
                data.put("msg",fileExtError);
                return data;
            } else if (picSize > Constants.ONE_HUNDRED_MB) {
                fileExtError = "视频最大100M";
                data.put("code","2");
                data.put("msg",fileExtError);
                return data;
            } else {
                // 对原文件名进行重命名
                fileName = UUIDUtil.uuid() + "." + fileExt;
                // 返回图片路径
                String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
                videoPath = Constants.NEWS_PATH + fileName;
                File dic = new File(rootPath + Constants.NEWS_PATH);
                if(!dic.exists()){
                    dic.mkdirs();
                }
                //上传至服务器
                String realPath = rootPath + videoPath;
                mf.transferTo(new File(realPath));
                data.put("video_name",orgFileName);
                data.put("video_path",videoPath.replace("\\","/"));
                return data;
            }
        }
        return data;
    }


    /**
     * 上传文件
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = (String) request.getParameter("path");
        //path为空默认放在新闻目录下
        if(ToolUtil.isEmpty(path)){
            path = Constants.NEWS_PATH;
        }else{
            //excel存储目录
            if(path.equals("excel")){
                path = Constants.EXCEL_PATH;
            }else{
                path = Constants.UPLOAD_PATH + path + File.separator;
            }
        }
        Map data = new HashMap() ;
        data.put("code",0);
        data.put("msg","上传成功");
        // 视频路径
        String filePath = "";
        // 视频名称
        String orgFileName = null;
        // 视频后缀
        String fileExt = null;
        // 文件格式错误信息
        String fileExtError = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            // 获取图片大小
            long picSize = mf.getSize();
            // 获取原文件名
            orgFileName = mf.getOriginalFilename();
            String fileName =  mf.getOriginalFilename();
            // 获取图片后缀
            fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Constants.RAR.equals(fileExt) && !Constants.ZIP.equals(fileExt) && !Constants.TXT.equals(fileExt) && !Constants.PDF.equals(fileExt)
                    && !Constants.PPT.equals(fileExt) && !Constants.PPTX.equals(fileExt) && !Constants.DOC.equals(fileExt) && !Constants.DOCX.equals(fileExt)
                    && !Constants.XLS.equals(fileExt) && !Constants.XLSX.equals(fileExt)) {
                fileExtError = "不支持的文件格式";
                data.put("code","1");
                data.put("msg",fileExtError);
                return data;
            } else if (picSize > Constants.ONE_HUNDRED_MB) {
                fileExtError = "文件最大100M";
                data.put("code","2");
                data.put("msg",fileExtError);
                return data;
            } else {
                // 对原文件名进行重命名
                fileName = UUIDUtil.uuid() + "." + fileExt;
                // 返回图片路径
                String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
                filePath = path + fileName;
                File dic = new File(rootPath + path);
                if(!dic.exists()){
                    dic.mkdirs();
                }
                //上传至服务器
                String realPath = rootPath + filePath;
                mf.transferTo(new File(realPath));
                data.put("file_name",orgFileName);
                data.put("file_path",filePath.replace("\\","/"));
                return data;
            }
        }
        return data;
    }



    @RequestMapping(value = "/uploadStatus")
    @ResponseBody
    public Integer uploadStatus(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object percent = session.getAttribute("upload_percent");
        return null != percent ? (Integer) percent : 0;
    }

    /**
     * 跳转裁切页面
     * @param imgPath
     * @param model
     * @return
     */
    @RequestMapping(value = "/toCut")
    public String toCut(String imgPath,String width,String height,Model model){

        model.addAttribute("imgPath",imgPath);
        model.addAttribute("width",width);
        model.addAttribute("height",height);

        return PREFIX + "cutImage.html";
    }

    /**
     * 裁切
     * @param request
     * @return
     */
    @RequestMapping(value = "/cutImage")
    @ResponseBody
    public Map<String,Object> cutImage(HttpServletRequest request){
        //坐标
        int x = 0;
        int y = 0;
        int w = 0;
        int h = 0;

        String xs = getHttpServletRequest().getParameter("x");
        String ys = getHttpServletRequest().getParameter("y");
        String ws = getHttpServletRequest().getParameter("w");
        String hs = getHttpServletRequest().getParameter("h");
        String imgPath = getHttpServletRequest().getParameter("imgPath");

        //裁剪坐标
        if(ToolUtil.isNotEmpty(xs)){
            x = Integer.parseInt(xs.indexOf(".") >= 0 ? xs.substring(0, xs.indexOf(".")) : xs);
        }
        if(ToolUtil.isNotEmpty(ys)){
            y = Integer.parseInt(ys.indexOf(".") >= 0 ? ys.substring(0, ys.indexOf(".")) : ys);
        }
        if(ToolUtil.isNotEmpty(ws)){
            w = Integer.parseInt(ws.indexOf(".") >= 0 ? ws.substring(0, ws.indexOf(".")) : ws);
        }
        if(ToolUtil.isNotEmpty(hs)){
            h = Integer.parseInt(hs.indexOf(".") >= 0 ? hs.substring(0, hs.indexOf(".")) : hs);
        }

        //获取后缀
       String fileExt = imgPath.substring(imgPath.lastIndexOf(".") + 1).toLowerCase();
        Map<String,Object> map = cut(imgPath,fileExt,request,x,y,w,h);
       return map;
    }

    /**
     * 裁切
     * @param fileName
     * @param fileExt
     * @param request
     * @param x
     * @param y
     * @param w
     * @param h
     * @return
     */
    public  Map<String,Object> cut(String fileName,String fileExt,HttpServletRequest request,int x,int y,int w,int h){
        boolean flag = false;
        String ctxPath = Constants.BLANK;
        Map<String,Object> map = new HashMap<String,Object>();

        // 获取路径
        String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
        ctxPath = rootPath + fileName;
        // 裁切
        flag = ImgCut.cutImg(ctxPath, ctxPath,fileExt, x, y, w, h);
        if(flag){//裁切成功
            File dic = new File(rootPath + Constants.NEWS_PATH);
            if(!dic.exists()){
                dic.mkdirs();
            }
            map.put("result","success");
        }else{
            map.put("result","error");
        }
        return map;
    }

}
